package tmt.usercenter.web.service;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tmt.usercenter.web.domain.TmtAuthority;
import tmt.usercenter.web.domain.TmtRole;
import tmt.usercenter.web.domain.TmtRoleAuthority;
import tmt.usercenter.web.repository.ITmtRoleAuthorityRepo;

import javax.persistence.criteria.Predicate;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class TmtRoleAuthorityService extends TmtBaseService<TmtRoleAuthority, Long> {

    @Getter
    private ITmtRoleAuthorityRepo iTmtRoleAuthorityRepo;

    @Autowired
    public TmtRoleAuthorityService(ITmtRoleAuthorityRepo iTmtRoleAuthorityRepo){
        super(iTmtRoleAuthorityRepo, new ArrayList<>());
        this.iTmtRoleAuthorityRepo = iTmtRoleAuthorityRepo;
    }

    /**
     * 删除指定权限ID的所有相关记录。
     * @param authorityId
     */
    public void deleteByAuthorityId(Long authorityId){
        Specification<TmtRoleAuthority> s = (root, query, cb) -> {
            Predicate p = cb.equal(root.get("authority").get("id"), authorityId);
            return query.where(p).getRestriction();
        };
        List<TmtRoleAuthority> list = iTmtRoleAuthorityRepo.findAll(s);
        iTmtRoleAuthorityRepo.deleteInBatch(list);
    }

    public void deleteByRoleId(long roleId){
        Specification<TmtRoleAuthority> s = (root, query, cb) -> {
            Predicate p = cb.equal(root.get("role").get("id"), roleId);
            return query.where(p).getRestriction();
        };
        List<TmtRoleAuthority> list = iTmtRoleAuthorityRepo.findAll(s);
        iTmtRoleAuthorityRepo.deleteInBatch(list);
    }

    @Transactional(readOnly = true)
    public List<TmtRoleAuthority> findByRoleId(Long roleId){
        Specification<TmtRoleAuthority> s = (root, query, cb) -> {
            Predicate p = cb.equal(root.get("role").get("id"), roleId);
            return query.where(p).getRestriction();
        };
        return iTmtRoleAuthorityRepo.findAll(s);
    }

}
